package com.example.serialportdemo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * @auth: njb
 * @date: 2023/12/31 12:37
 * @desc: 描述
 */
public class AirConditionerDisplayView  extends View {
    private float width;

    /**
     * 总颜色显示
     */
    private Paint allPaint;

    private int allColor = Color.WHITE;
    /**
     * 扫过颜色显示
     */
    private Paint swipePaint;
    private int swipeColor = Color.RED;

    /**
     * 刻度密集度  默认是2  代表着1℃ = 2刻度
     */
    private int mDensity = 3;

    /**
     * 最小温度
     */
    private float minTemp = 10;

    /**
     * 最大温度
     */
    private float maxTemp = 20;

    /**
     * 当前温度
     */
    private float nowTemp = -1;

    /**
     * 扫过的角度
     */
    private float swipeAllAngle = 300;


    /**
     * 椭圆的长度
     */
    private float mLength = 30;

    /**
     * 椭圆的宽度
     */
    private float mWidth = 10;

    /**
     * 椭圆的圆角
     */
    private float mReduce = 10;

    /**
     * 间距
     */
    private float mPadding = 20;

    /**
     * 当前绘制刻度 进度
     */
    private int drawIndex = 0;


    /**
     * 初始动画时间
     */
    private long startTotalTime = 500;

    /**
     * 加减动画时间
     */
    private long normalTime = 50;


    /**
     * 渐变色 开始颜色
     */
    private int startColor = -1;
    /**
     * 结束 开始颜色
     */
    private int endColor = -1;

    public void setReduce(float reduce) {
        mReduce = reduce;
    }

    public void setAllScaleColor(int allColor) {
        this.allColor = allColor;
        allPaint.setColor(allColor);
    }

    public void setSwipeScaleColor(int swipeColor) {
        this.swipeColor = swipeColor;
        swipePaint.setColor(swipeColor);
    }

    public void setStartColor(int startColor) {
        this.startColor = startColor;
    }

    public void setEndColor(int endColor) {
        this.endColor = endColor;
    }

    public float getNowTemp() {
        return nowTemp;
    }

    public void setScaleLength(float mLength) {
        this.mLength = mLength;
    }

    public void setScaleWidth(float mWidth) {
        this.mWidth = mWidth;
    }

    public void setPadding(float mPadding) {
        this.mPadding = mPadding;
    }

    public void setSwipeMaxAngle(float swipeAllAngle) {
        this.swipeAllAngle = swipeAllAngle;
    }

    public void setDensity(int mDensity) {
        this.mDensity = mDensity;
    }

    public float getMinTemp() {
        return minTemp;
    }

    public void setMinTemp(float minTemp) {
        this.minTemp = minTemp;
    }

    public float getMaxTemp() {
        return maxTemp;
    }

    public void setMaxTemp(float maxTemp) {
        this.maxTemp = maxTemp;
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public void setStartAnimlTime(long startTotalTime) {
        this.startTotalTime = startTotalTime;
    }

    public void setAnimTime(long normalTime) {
        this.normalTime = normalTime;
    }

    public AirConditionerDisplayView(Context context) {
        this(context, null);
    }

    public AirConditionerDisplayView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AirConditionerDisplayView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        allPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        allPaint.setColor(allColor);
        allPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        swipePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        swipePaint.setColor(swipeColor);
        swipePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        drawIndex = 0;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int wSize = MeasureSpec.getSize(widthMeasureSpec);
        int hSize = MeasureSpec.getSize(heightMeasureSpec);
        int min = Math.min(wSize, hSize);
        setMeasuredDimension(min, min);
        Log.v("AirTemperatureShowView", "wSize=" + wSize + ";hSize=" + hSize);
    }

    /**
     * @return 索取开始动画时间
     */
    private long getStartAnimTime() {
        int nowNum = getDrawNowNum();
        return startTotalTime / nowNum;
    }

    /**
     * @return 加减动画时间
     */
    private long getNormalTime() {
        return normalTime / mDensity;
    }

    /**
     * @return 绘制的刻度总个数
     */
    private int getDrawAllNum() {
        int i = (int) (Math.abs((maxTemp - minTemp)) * mDensity);
        if (i % 2 == 0) {
            i += 1;
        }
        return i;
    }

    /**
     * @return 绘制的当前刻度总个数
     */
    private int getDrawNowNum() {
        int count = (int) (Math.abs((nowTemp - minTemp)) * mDensity);
        return count<=0?1:count;
    }

    /**
     * @return 获取每一次旋转角度
     */
    @SuppressLint("LongLogTag")
    private float getEveryAngleSwipe() {
        if (swipeAllAngle <= 180) {
            swipeAllAngle = 235;
        }
        if (swipeAllAngle / getDrawAllNum() < 3) {
            swipeAllAngle = 235;

        } else {
            return swipeAllAngle / getDrawAllNum();
        }

        Log.d("AirTemperatureShowView == >", " 每次转动角度 " + swipeAllAngle / getDrawAllNum() + " getDrawAllNum = " + getDrawAllNum());
        return swipeAllAngle / getDrawAllNum();
    }

    /**
     * @return 获取开始绘制角度
     */
    private float getStartSwipeAngle() {
        if (swipeAllAngle <= 180) {
            swipeAllAngle = 235;
        }
        return 180 - (swipeAllAngle - 180) / 2.f - 90;
    }

    /**
     * 降温
     */
    public void reduceTemp() {
        if (nowTemp <= minTemp) {
            return;
        }
        nowTemp = nowTemp - 1;
        start(getNormalTime());
    }

    /**
     * 升温
     */
    public void addTemp() {
        if (nowTemp >= maxTemp) {
            return;
        }
        nowTemp = nowTemp + 1;
        start(getNormalTime());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        width = getWidth();
        drawingRect(canvas);
    }


    private Path mPath;
    private RectF addRoundRect;
    private float canvasRotate = 0;//画布旋转的 总角度

    private void drawingRect(Canvas canvas) {
        canvas.translate(width / 2f, width / 2f);
        width = width - mPadding;
        canvas.rotate(getStartSwipeAngle());
        canvas.save();
        mPath = new Path();
        addRoundRect = new RectF();
        addRoundRect.left = -mWidth / 2.f;
        addRoundRect.right = mWidth / 2.f;
        addRoundRect.top = width / 2f - mLength;
        addRoundRect.bottom = width / 2f;
        mPath.addRoundRect(addRoundRect, mReduce, mReduce, Path.Direction.CW);//画一个实心椭圆
        float allNum = getDrawAllNum();
        for (int i = 0; i < allNum; i++) {
            canvas.drawPath(mPath, allPaint);
            if (i <= drawIndex) {
                dealColor(addRoundRect, i);
                canvas.drawPath(mPath, swipePaint);
            } else {
                canvas.drawPath(mPath, allPaint);
            }
            canvas.rotate(getEveryAngleSwipe());
        }
        canvas.restore();
    }

    /**
     * 处理渐变色
     *
     * @param addRoundRect
     * @param i
     */
    private void dealColor(RectF addRoundRect, int i) {
        if (startColor == -1) {
            startColor = swipePaint.getColor();
        }
        if (endColor == -1) {
            endColor = allPaint.getColor();
        }
        LinearGradient gradient = new LinearGradient(addRoundRect.right, 0, addRoundRect.left, 0, getColorChange(swipeColor, allColor, i), getColorChange(startColor, endColor, i + 1), Shader.TileMode.CLAMP);
        swipePaint.setShader(gradient);
    }

    /**
     * @param temp 温度初始值
     */
    public void setTemp(String temp) {
        try {
            setTemp(Integer.valueOf(temp));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param temp 温度初始值
     */
    public void setTemp(float temp) {
        if (nowTemp == -1) {
            nowTemp = temp;
            start(getStartAnimTime());
        } else {
            nowTemp = temp;
            start(getNormalTime());
        }

    }


    /**
     * 开始执行加载动画
     */
    private void start(final long time) {
        Log.d("AirTemperatureShowView", " 当前刻度数目 " + drawIndex + " 最大刻度数 = " + getDrawAllNum() + " 当前刻度数 " + getDrawNowNum() + "  drawIndex < getDrawNowNum() = " + (drawIndex < getDrawNowNum()));
        postDelayed(new Runnable() {
            @Override
            public void run() {
//                当前绘了多少温度的刻度
                if (drawIndex < getDrawNowNum()) {
//                    addTemp();
                    drawIndex++;
                    postInvalidate();
                    start(time);
                } else if (drawIndex > getDrawNowNum()) {
                    drawIndex--;
                    postInvalidate();
                    start(time);
                }
            }
        }, time);
    }

    /**
     * 颜色拆分 runNum 索取指定位置颜色
     * 从color1 渐变到 color2,以下是一种颜色到另一种颜色需要执行Num次才能彻底渐变结束；
     *
     * @return
     */
    private int getColorChange(int startColor, int endColor, int index) {
        int R, G, B;
        // 颜色的渐变，应该把分别获取对应的三基色，然后分别进行求差值；这样颜色渐变效果最佳
        R = Color.red(startColor) + (Color.red(endColor) - Color.red(startColor)) * index / getDrawAllNum();
        G = Color.green(startColor) + (Color.green(endColor) - Color.green(startColor)) * index
                / getDrawAllNum();
        B = Color.blue(startColor) + (Color.blue(endColor) - Color.blue(startColor)) * index
                / getDrawAllNum();
        return Color.rgb(R, G, B);
    }

}
